<?php
#status 0: Offline
# status 1: not in Game

# status 5: in Game, Waiting for Starting
# status 6: Starting Status 

# status: 10 Running Game


class class_risk {

	var $CurrentGame 	= "";
	var $bottomsrc 		= "";
	
	function get_soapobject() {
		global $CONFIG;
		require_once 'SOAP/Client.php';
		$wsdl 		 = new SOAP_WSDL ($CONFIG['risk']['master']['wsdl']);		
		$Client 	= $wsdl->getProxy();
		return $Client;
	}
	
	function soapUpdateNumOnline($numonline) {
		global $CONFIG;	
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->updateNumOnline($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey'],"$numonline");
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: index.php");
				exit;
			}
		} 
	}
	
	function soapUpdateCurrentGame($currentgame) {
		global $CONFIG;
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->updateCurrentGame($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey'],"$currentgame");
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: index.php");
				exit;
			}
		} 	
	}
	
	function soapUserLogin($username,$password) {
		global $CONFIG;		
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->userLogin($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey'],$username,$password);
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: index.php");
				exit;
			} else if($msg == "nouser") {
				$_SESSION['msg'] = " Your Username and/or Password is invalid (Connected to Master).";
				header ("Location: index.php");
				exit;			
			}
			$data = explode("|next|",$msg);
			$num = $data[0];
			$email = $data[1];
			$cdb = new class_mysql;
			$cdb->select("select * from risk_players where num = '$num' ");
			if($cdb->getRecords() == 0) {
				$cdb->insert("insert into risk_players (`num`,username,password,email) values 
				('$num','$username','$password','$email')");
			} else {
				$cdb->update("update risk_players set username='$username', password='$password', email='$email'
				where num='$num'");				
			}
		} 
	}
	function soapUserLogout($usernum) {
		global $CONFIG;	
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->userLogout($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey'],"$usernum");
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: index.php");
				exit;
			} else if($msg == "error") {
				$_SESSION['msg'] = " Logout failed (Connected to Master).";
				header ("Location: index.php");
				exit;			
			}
		} 
	}
	
	function soapUserUpdateLog($usernum) {
		global $CONFIG;		
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->userUpdateLog($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey'],"$usernum");
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: index.php");
				exit;
			}
		} 
	}	
	
	function soapUserRegister($username,$userpass,$useremail) {
		global $CONFIG;		
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->userRegister($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey'],
			$username,$userpass,$useremail);
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: register.php");
				exit;
			}
			if($msg == "userexists") {
				$_SESSION['msg'] = " A user with this username or password already exists!";
				header ("Location: register.php");
				exit;
			}
			$_SESSION['msg'] = "User $msg added successfully";
			header("Location: index.php");
			exit;
		} 
		return false;
	}	
	
	function soapUserChangepass($usernum,$oldpass,$newpass) {
		global $CONFIG;		
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->userChangepass($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey'],
			$usernum,$oldpass,$newpass);
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: changepw.php");
				exit;
			}
			if($msg == "currentpassworddoesnotmatch") {
				$_SESSION['msg'] = "Current password on Risk Master does not match!";
				header ("Location: changepw.php");
				exit;
			}
		} 
	}	
		
	function get_style_link(){
		global $CONFIG;
		$path 	= $this->style_path;
		$style 	= $this->style_file;
		$result = "<link rel=\"stylesheet\" type=\"text/css\" href=\"$path/$style\" >";
		return $result;
	}
	
	function risk_login() {
		global $CONFIG;
		$cdb 		= new class_mysql;
		$username 	= $_REQUEST['username'];
		$password 	= $_REQUEST['password'];	
		if(isset($_REQUEST['md5password'])) {
			$password 	= $_REQUEST['md5password'];	
		} else {
			$password = md5($password);
		}
		$this->soapUserLogin($username,$password);
		$cdb->select("SELECT num, username, level FROM risk_players WHERE username='$username' AND password='$password'");  		
		if ($cdb->getRecords() == 0) {			
			$_SESSION['msg'] = " Your Username and/or Password is invalid.";
			header ("Location: index.php");
			exit;
		} else {
			$row = $cdb->fetchArray();
			$_SESSION['RISK_USERNUM']   = $row['num'];
			$_SESSION['RISK_USERNAME']  = $row['username'];
			$_SESSION['RISK_USERLEVEL'] = $row['level']; 
			$cdb->update("UPDATE risk_players SET status='1', stamp='".time()."' WHERE num='".$row['num']."'");
			header ("Location: index.php");
			exit;
		}
	}	
	
	function loginCheck() {	
		global $CONFIG;
		$cdb 	 = new class_mysql;	
		$timeout = time() - 900;
		$cdb->select("SELECT COUNT(*) AS NumOnline FROM risk_players WHERE status > '0' AND stamp > '$timeout'");
		$row 	 = $cdb->fetchArray();
		$cdb->update("UPDATE risk_config SET NumOnline='".$row['NumOnline']."'");
		$this->soapUpdateNumOnline($row['NumOnline']);
		
		if (isset($_SESSION['RISK_USERNUM']) && $_SESSION['RISK_USERNUM'] != $null) {
			$cdb->select("SELECT stamp FROM risk_players WHERE num='".$_SESSION['RISK_USERNUM']."'");
			$row 	 = $cdb->fetchArray();
			if ((time() - $row['stamp']) > 900) {
				$_SESSION['msg'] = 'You have been logged out for inactivity.';
				$this->risk_logout();		
			} else {
				$cdb->update("UPDATE risk_players SET stamp='".time()."' WHERE num='".$_SESSION['RISK_USERNUM']."'");		
			}
		} else {
			header("Location:index.php");
			exit;
		}
	}
	
	function risk_logout() {
		global $CONFIG;
		$cdb 	 = new class_mysql;			
		$cdb->update("UPDATE risk_players SET status='0' WHERE num='".$_SESSION['RISK_USERNUM']."'");
		$this->soapUserLogout($_SESSION['RISK_USERNUM']);
		$_SESSION['RISK_USERNUM']     = $null;
		$_SESSION['RISK_USERNAME']    = $null;
		$_SESSION['RISK_USERLEVEL']   = $null;
		header ("Location: index.php");
		exit;
	}
			
	
	
	// Sets this->CurrentGame 
	// Updates Users stamp and status
	// Sets $_SESSION[''RISK_TURNORDER']
	// Sets $this->bottomsrc
	// Inserts Join Message into table risk_log
	
	function risk_init(){
		global $nojoin;
		unset($_SESSION['RISK_LASTREQUEST']);
		unset($_SESSION['RISK_LASTCHATREQUEST']);
		$cdb 		= new class_mysql;
		if(($_POST['selcolor']) && ($_POST['maptype'])) {
			$cdb->select("select assigned from risk_colors where colornum = '".$_POST['selcolor']."'");
			$daten = $cdb->fetchArray();
			if($daten[0] <= 6) {
				$_SESSION['maptype'] = $_POST['maptype'];
				$this->assignColor($_SESSION['RISK_USERNUM'],$_POST['selcolor']);
				$this->check4botmove();
			} else { $_SESSION['msg'] = "Sorry, this color is assigned to another Player";	}
		}		
		$cdb->select("SELECT CurrentGame FROM risk_config");
		$row 				= $cdb->fetchArray();
		$CurrentGame		= $row['CurrentGame'];
		$this->CurrentGame 	= $CurrentGame;		
		$cdb->update("UPDATE risk_players SET stamp='".time()."', status='5' WHERE num='".$_SESSION['RISK_USERNUM']."'");		
		if($CurrentGame != "Starting") {
			$cdb->update("UPDATE risk_players SET status='10' WHERE num='".$_SESSION['RISK_USERNUM']."'");
			$cdb->select("SELECT color, turnorder, bottomsrc FROM risk_players WHERE num='".$_SESSION['RISK_USERNUM']."'");
			$row 						= $cdb->fetchArray();
			$_SESSION['RISK_TURNORDER'] = $row['turnorder'];
			$this->bottomsrc  			= $row['bottomsrc'];
			if($nojoin != 'true'){
				$color 		  				= $row['color'];
				$risk_log_msg 				= "<b><font color=$color>* ".$_SESSION['RISK_USERNAME']." has joined.</font></b>";
				$cdb->insert("INSERT INTO risk_log VALUES('', '".date("Y-m-d H:i:s")."','$risk_log_msg') ");
			}
		}
		return $CurrentGame;
	}
	
	function risk_kick($who, $why, $kickedby) {
		$cdb   			= new class_mysql;	
		// LOG
		$cdb->select("SELECT username, color, turnflag FROM risk_players WHERE num='$who'");
		$row 		= $cdb->fetchArray();
		$tocol 		= $row['color'];
		$to 		= $row['username'];
		$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\", \"<b><font color='gray'>* $kickedby kicked
					<font color='$tocol'>$to</font>. Reason: $why</font></b>\")");
		
		$cdb->update("UPDATE risk_players SET kickflag='$kickedby $why', status='1' WHERE num='$who'");	
		$cdb->select("SELECT colornum FROM risk_colors WHERE assigned='$who'");
		$row 		= $cdb->fetchArray();
		$colornum 	= $row['colornum'];					
		$cdb->select("select num from risk_players where num < 7 and turnorder=0 limit 1");
		$daten 		= $cdb->fetchArray();
		$this->assignColor($daten['num'], $colornum);
		$this->check4botmove();				
		// ADD UNFINISHED
		$cdb->select("SELECT unfinished FROM risk_players WHERE num='$who'");
		$row 			= $cdb->fetchArray();
		$unfinished 	= $row['unfinished'] + 1;
		$cdb->query("UPDATE risk_players SET unfinished='$unfinished' WHERE num='$who'");
		return true;				
	}

	function risk_start() {
		$cdb = new class_mysql;
		// CHANGE PLAYER STATUS
		$cdb->update("UPDATE risk_players SET status='6', bottomsrc='deploy.php' WHERE status='5'");
		
		// SET RANDOM ORDER AND COLORS
		$autodeploy = $_POST['autodeploy'];
		$startarmies = $_POST['startarmies'];
		$numplayers = $_POST['numplayers'];
		#$numplayers = 6;
		$cdb->select("SELECT num FROM risk_players WHERE status='6'");
		//$numplayers = $cdb->getRecords();
		for ($i=0; $row = $cdb->fetchArray(); $i++){
			$order[$i] = $row['num'];
		}
		$j = 1;
		for($i = $i; $i < $numplayers; $i++) {		
			$cdb->select("SELECT color FROM risk_colors WHERE assigned='0' limit 1");
			$row      = $cdb->fetchArray();
			$color    = $row['color'];
			$cdb->query("UPDATE risk_colors SET assigned='$j' WHERE color='$color'");			
			$cdb->query("UPDATE risk_players SET color='$color', status = '10' WHERE num='$j'");			
			$order[$i] = $j;
			$j++;
		}
		srand((float)microtime()*1000000);
		shuffle($order);
		
		// DETERMINE NUMBER OF ARMIES
		switch($numplayers) {
			case '1': $numarmies = 45; break;
			case '2': $numarmies = 35; break;
			case '3': $numarmies = 35; break;
			case '4': $numarmies = 30; break;
			case '5': $numarmies = 25; break; 
			case '6': $numarmies = 20; break;
		}
		$numarmies = $numarmies + $startarmies;
		
		$cardsperplayer = floor(42 / $numplayers);
		$numarmies -= $cardsperplayer;
		for ($i=0; $i < $numplayers; $i++){
			$cdb->select("SELECT color FROM risk_colors WHERE assigned='".$order[$i]."'");
			$row 	= $cdb->fetchArray();
			$j 	 	= $i + 1;
			$cdb->update("UPDATE risk_players SET turnorder='$j', color='".$row['color']."', armies='$numarmies' WHERE num='".$order[$i]."'");
		}
		
		// DISTRIBUTE COUNTRY CARDS
		$cdb->select("SELECT num FROM risk_cards WHERE num <= '42'");
		for ($i=0; $row = $cdb->fetchArray(); $i++){
		 $cards[$i] = $row['num'];
		}
		srand((float)microtime()*1000000);
		shuffle($cards);
		$c = 0;
		for ($i=0; $i < $numplayers; $i++){
		 for ($j=0; $j < $cardsperplayer; $j++) {
		  $cdb->update("UPDATE risk_countries SET owner='".$order[$i]."', armies='1' WHERE num='".$cards[$c]."'");
		  $c++;
		 }
		}
		
		
		// CHECK CONTINENTS
		SetContinentOwners();
		
		// SET ALLIES
		#$cdb->update("UPDATE risk_countries SET owner='1', armies='2' WHERE owner <= '1'");
		
		// DEPLOY
		#$cdb->update("UPDATE risk_players SET armies='$numarmies' WHERE status='6'");
		$cdb->update("UPDATE risk_cards SET owner='0'");
		$cdb->update("UPDATE risk_players SET turnflag='1' WHERE turnorder='1'");
		$cdb->update("UPDATE risk_config SET CurrentGame='Deploying', TurnStatus='Deploying'");	
		$this->soapUpdateCurrentGame('Deploying');
		
		$cdb2 	 = new class_mysql;			
		if($autodeploy == 1) {
			$cdb->select("select armies, num from risk_players where turnorder > '0' order by turnorder");
			while($daten = $cdb->fetchArray()) {
				$armies = $daten[0];
				$anum 	= $daten[1];
				
				for($i = 0; $i<$armies;$i++) {
					$cdb2->select("select armies,num from risk_countries where owner = '$anum' ORDER BY RAND() Limit 1 ");
					$d = $cdb2->fetchArray();
					$oa 	= $d[0];
					$cnum 	= $d[1];
					$oa++;
					$cdb2->update("update risk_countries set armies = '$oa' where num='$cnum'");				
				}
			}
			$cdb->update("update risk_players set armies = '0' where turnorder > '0'");
			$cdb->query("UPDATE risk_config SET CurrentGame='Active', TurnStatus='NewTurn'");
			$this->soapUpdateCurrentGame('Active');
	
		#	$cdb->select("select num from risk_players where turnflag = '1' ");
		#	$d = $cdb->fetchArray();
		#	$dnum = $d[0];
		#	ActionNewTurn($dnum);
			#NextPlayersTurn();
			
			
		}
		$this->check4botmove();
	}
	
	
	
	function risk_launch() {
		if(isset($_GET['action']) && ($_GET['action']=='launch')) {
			$cdb 	 = new class_mysql;			
			$cdb->select("SELECT CurrentGame FROM risk_config");
			$row 	= $cdb->fetchArray();		
			if ($row['CurrentGame'] == "Starting") {
				$_SESSION['launch'] = true;				
			} elseif ($row['CurrentGame'] == "Deploying" || $row['CurrentGame'] == "Active") {
				$cdb->select("SELECT turnorder FROM risk_players WHERE num='".$_SESSION['RISK_USERNUM']."'");
				$row 	= $cdb->fetchArray();	
				if ($row['turnorder'] > 0) {
					$cdb->update("UPDATE risk_players SET rejoinflag='1' WHERE num='".$_SESSION['RISK_USERNUM']."'");
					$_SESSION['launch'] = true; 
				} else { $_SESSION['launch'] = true; }				
			} else { $_SESSION['msg'] = "There is no match starting."; }
			header ("Location: index.php");
			exit;
		}
	}
	
	function risk_spectate() {
		if(isset($_GET['action']) && ($_GET['action']=='spectate')) {
			$cdb 	 = new class_mysql;			
			$cdb->select("SELECT CurrentGame FROM risk_config");
			$row 	= $cdb->fetchArray();					
			if ($row['CurrentGame'] == "Active" || $row['CurrentGame'] == "Deploying") {
				$_SESSION['spectate'] = true;
			} else {
				$_SESSION['msg'] = "There is no match in progress.";
			}
			header ("Location: index.php");
			exit;
		}
	}
	
	function risk_newmatch() {
		if(isset($_GET['action']) && ($_GET['action']=='newmatch')) {
			$cdb 	 	= new class_mysql;	
			$cdb->select("SELECT CurrentGame from risk_config");
			$row 		= $cdb->fetchArray();					
			if ($row['CurrentGame'] == 'Inactive') {
				$cdb->update("UPDATE risk_players SET color='', armies='0', cardflag='0', kickflag=NULL, turnorder='0', turnflag='0', status='1'");
				$cdb->update("UPDATE risk_players SET color='white' WHERE num='1'");
				$cdb->update("UPDATE risk_config SET CurrentGame='Starting', StartedBy='".$_SESSION['RISK_USERNAME']."', TradeIndex='0'");
				$this->soapUpdateCurrentGame('Starting');
				$cdb->update("UPDATE risk_countries SET owner='0'");
				$cdb->update("UPDATE risk_continents SET owner='0'");
				$cdb->update("UPDATE risk_colors SET assigned='0'");
				$cdb->update("UPDATE risk_cards SET owner='0'");
				$cdb->update("TRUNCATE TABLE risk_dialog");
				$cdb->update("TRUNCATE TABLE risk_log");
				$msg 		= "The match will start momentarily.";
				$_SESSION['launch'] = '1';			
				$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
						 \"<b><font color='gray'>* Match started by ".$_SESSION['RISK_USERNAME'].".</font></b>\")");
			} else {  $msg = "There is already a match in progress."; }
			$_SESSION['msg'] = $msg;
			header ("Location: index.php");
			exit;
		}
	}
	
	
	function risk_endmatch() {
		global $CONFIG;
		if(isset($_GET['action']) && ($_GET['action']=='endmatch')) {
			$cdb 	 	= new class_mysql;	
			$cdb2 	 	= new class_mysql;	
			if ($_SESSION['RISK_USERLEVEL'] < '3') {
				$_SESSION['msg'] = "Access denied!";
				header ("Location: index.php");
				exit;
			}
			$cdb->select("SELECT CurrentGame FROM risk_config");
			$row = $cdb->fetchArray();			
			if ($row['CurrentGame'] == 'Inactive') {
				$msg = "There is no active match.";
			} else {
				$cdb->update("UPDATE risk_config SET CurrentGame='Inactive', TurnStatus='".$_SESSION['RISK_USERNAME']."'");
				$this->soapUpdateCurrentGame('Inactive');
				$cdb->select("SELECT num, unfinished FROM risk_players WHERE status='10'");
				
				while ($row = $cdb->fetchArray()) {
					$u = $row['unfinished'] + 1;
					$cdb2->update("UPDATE risk_players SET unfinished='$u', status='1' WHERE num='".$row['num']."'");
				}		
				$cdb->insert("INSERT INTO risk_log VALUES(\"\", \"".date("Y-m-d H:i:s")."\",
						 \"<b><font color='gray'>* Match killed by ".$_SESSION['RISK_USERNAME'].".</font></b>\")");
			
				$msg = "Match killed successfully.";
			
				// OUTPUT LOG.
				$openfile = "risklogs/" .date("Ymd-His").".html";
				$LOG = fopen($openfile, "w");
				if ($LOG) {
				   $cdb->select("SELECT * FROM risk_log");
				   fwrite($LOG, $GLOBALS['log_header']);	
				   fwrite($LOG, "<table>");
				 
				   while ($row = $cdb->fetchArray()) {
					fwrite($LOG, "<tr><td style='text-align:left'><font size='2'><font color='gray'>". $row['stamp'] ."</font> </td><td>". $row['log'] ."</font></td></tr>");
				   }
				   fwrite($LOG, "</table>");
				   fwrite($LOG, $GLOBALS['log_footer']);
				   fclose($LOG);
				} else {  $msg .= "<br>Failed to open log file for write access.";  }
			}
			$_SESSION['msg'] = $msg;
			header ("Location: index.php");
			exit;
		}
	}	
	
	function changepw() {	
		$cdb = new class_mysql;	
		$msg = "";
		if($_POST['currentpassword'] == '' || $_POST['newpassword'] == '' || $_POST['confirmpassword'] == '') {
			$msg = "You must fill out all the fields.";
		} else {
			$newpassword 		= md5($_POST['newpassword']);
			$currentpassword 	= md5($_POST['currentpassword']);
			$cdb->select("SELECT 1 FROM risk_players WHERE num='".$_SESSION['RISK_USERNUM']."' 
						  AND password='$currentpassword'");
			if ($cdb->getRecords() == 0) {
				$msg = "Current password does not match.";
			} else {
				if ($_POST['newpassword'] == $_POST['confirmpassword']) {
					$this->soapUserChangepass($_SESSION['RISK_USERNUM'],$currentpassword,$newpassword);
					$cdb->select("UPDATE risk_players SET password='$newpassword' 
								  WHERE num='".$_SESSION['RISK_USERNUM']."'");
				} else{ $msg = "New passwords do not match."; }
		   }
		}		
		if ($msg == "") {
		  $_SESSION['msg'] = "Password changed successfully.";
		  header("Location: index.php");
		  exit;
		} else {
		  $_SESSION['msg'] = $msg;
		  header("Location: changepw.php");
		  exit;
		}
	}
	
	function register(){	
		$cdb = new class_mysql;
		$msg = "";
		if($_POST['username'] == '' || $_POST['password'] == '' || $_POST['confirmpassword'] == '' || $_POST['email'] == '') {
			$msg = "You must fill out all the fields.";
		} elseif ($_POST['password'] != $_POST['confirmpassword']) {
			$msg = "Passwords do not match";
		} else {
			$password = md5($_POST['password']);				
			$this->soapUserRegister($_POST['username'],$password,$_POST['email']);
						
			$cdb->select("SELECT 1 FROM risk_players WHERE username='".$_POST['username']."' OR email='".$_POST['email']."'");
			if ($cdb->getRecords() == 0) {
					$cdb->insert("INSERT INTO risk_players (`username`, `password`, `level`, `email`)
							  VALUES('".$_POST['username']."', '$password', '1', '".$_POST['email']."')");
			} else {  $msg = "There is already a user with this name or e-mail address."; }			
		}		
		if ($msg == "") {
			$_SESSION['msg'] = "User added successfully";
			header("Location: index.php");
			exit;
		} else {
			$_SESSION['msg'] = $msg;
			header("Location: register.php");
			exit;
		}	
	}
		
	function resetpw() {
		global $server;
		$cdb = new class_mysql;
		$msg = "";
		if($_POST['username'] == '' || $_POST['email'] == '') {
			$msg .= "You must fill out all the fields.";
		} else {
			$cdb->select("SELECT num, username, email FROM risk_players 
			 			  WHERE username='".$_POST['username']."'  AND email='".$_POST['email']."'");
			if ($cdb->getRecords() == 0) {
			  $msg .= "No user found with this name and e-mail address";
			} else {
				$row = $cdb->fetchArray();
				$password = mt_rand(10000000, 99999999);
				$reset = "Hello ". $row['username'] .",\n\nYour RiSK password was successfully reset.\nHere is your new password : $password\n\n-- http://$server";
				$password = md5($password);
				if(mail($row['email'], "PHP RiSK Password Reset", $reset)) {
					$cdb->update("UPDATE risk_players SET password='$password' 
								  WHERE num='".$row['num']."'");
				} else {
					$msg .= "An error occured while sending mail, password not reset.";
				}
			}
		}		
		if ($msg == "") {
			$_SESSION['msg'] = "Password reset successfully.";
			header("Location: index.php");
			exit;
		} else {
			$_SESSION['msg'] = $msg;
			header("Location: resetpw.php");
			exit;
		}
	}
	
	
	function adminChangeLevel() {
		$cdb 		= new class_mysql;	
		if ($_POST['username'] != '' && $_POST['level'] != '' && is_numeric($_POST['level'])) {
			if ($_SESSION['RISK_USERLEVEL'] < '3') { 
				$_SESSION['msg'] = "Access denied!";
				header ("Location: index.php");
				exit;
			}
			$cdb->select("SELECT 1 FROM risk_players WHERE username='".$_POST['username']."'");
			if ($cdb->getRecords() == 1) {
				$cdb->update("UPDATE risk_players SET level='".$_POST['level']."' WHERE username='".$_POST['username']."'");
				if ($_POST['username'] == $_SESSION['RISK_USERNAME']) {
					$_SESSION['RISK_USERLEVEL'] = $_POST['level'];
				}
				$msg = "Level changed successfully.";
			} else { $msg = "This user does not exists."; }
		} else { $msg = "The Username or Level was not specified or invalid."; }
		$_SESSION['msg'] = $msg;
		header ("Location: riskadmin.php");
		exit;
	}
	
	function adminDeleteUser() {
		$cdb 		= new class_mysql;	
		if ($_POST['confirm'] && $_POST['username'] != '')  {
			$cdb->select("SELECT 1 FROM risk_players WHERE username='".$_POST['username']."'");
			if ($cdb->getRecords() == 1)  {
				$cdb->query("DELETE FROM risk_players WHERE username='".$_POST['username']."'");
				$msg = "User deleted successfully.";
			} else { $msg = "This user does not exists."; }
		} else { $msg = "User not deleted: Confirm not checked or no Username specified."; }
		$_SESSION['msg'] = $msg;
		header ("Location: riskadmin.php");
		exit;
	}
	
	function DisplayLog($file) {
	 return substr($file, 0, 4) . "/" . substr($file, 4, 2) . "/" . substr($file, 6, 2) . " @ ". 
			substr($file, 9, 2) . ":" . substr($file, 11, 2);
	}
	
	
	function display_logfiles() {
		global $CONFIG;
		$r = "<h2>Game log</h2>";
		$i = 1;
		$show = "blank.html";
		$sel = "Matchlist<br>
		<select name=\"log\" onchange=\"document.getElementById('logsource').src = this.value;\">";
		if ($dir = @opendir("risklogs")) {
			while (($file = readdir($dir)) !== false) {
				if ($file != ".." && $file != ".") {
					if(!is_dir($file))  {
						$sel .= "<option value=\"risklogs/$file\">".$this->DisplayLog($file)."</option>";
						if($i ==1) { $show ="risklogs/$file"; }
						$i++;
						#$r .= "<a href='risklogs/$file' target='logsource'>".$this->DisplayLog($file)."</a><br>";
					}
				}
				}
			closedir($dir);
		}
		$sel .= "</select>";
		$r .= "
		$sel<br><br>
		<iframe name='logsource' id='logsource' width='380px' height='300px' src='$show' frameborder='0'></iframe>";	
		return $r;
	}
	
	
	function display_win() {	
		$cdb = new class_mysql;
		$cdb->select("SELECT CurrentGame FROM risk_config");
		$row = $cdb->fetchArray();
		if ($row['CurrentGame'] != "Complete") {
		  header("Location: index.php");
		}
		$cdb->select("SELECT username, color FROM risk_players WHERE status='10'");
		$row 	= $cdb->fetchArray();		
		$r 		=  "<h2>Game Over</h2>
		<center><br><br><br><font color='".$row['color']."' class=\"wintext\">".$row['username']." wins!<br><br><br></font></center>";
		return $r;
	}
	
	function display_gamelist() {
		global $CONFIG;
			$r = "<h2>Gamelist</h2>";
		if($CONFIG['risk']['master']['enable'] == true) {
			$soap 	 = $this->get_soapobject();
			$msg 	 = $soap->getGames($CONFIG['risk']['master']['gameid'],$CONFIG['risk']['master']['gamekey']);
			if($msg == "accessdenied") {
				$_SESSION['msg'] = " Webservice Access Denied!";
				header ("Location: index.php");
				exit;
			}
			$msg = explode("|nextGame|",$msg);
				$r .= "<table width=\"380px\">";
				$r .= "<tr><th>ID</th><th>Path</th><th>Game Status</th><th>Online User</th></tr>";
				if(count($msg) > 0) {
				for($i =0; $i<count($msg);$i++) {
					$daten = explode("|next|",$msg[$i]);
					$id = $daten[0];
					$key = $daten[1];
					$path = $daten[2];
					$CurrentGame = $daten[3];
					$NumOnline = $daten[4];
					$name = $daten[5];
					if($id == $CONFIG['risk']['master']['gameid']) { 
						$style="style=\"border:1px solid red;\""; 
					} else { $style = ""; }
					$np = $this->getUserNamePass($_SESSION['RISK_USERNUM']);
					$r .= "<tr><td $style>$id</td><td $style><a href=\"".$path."index.php?action=login&username=".$np[0]."&md5password=".$np[1]."\">$name</a></td>
					<td $style>$CurrentGame</td><td $style>$NumOnline</td></tr>";
				}
				$r .= "</table>";
			}
		} 
		return $r;
	}
	
	
	function display_gameManager() {
		global $PHP_SELF, $CONFIG;
		$this->risk_launch();
		$this->risk_spectate();
		$this->risk_newmatch();
		$this->risk_endmatch();
		$null 	= NULL;		
		$result = "";
		if (isset($_SESSION['launch']) && $_SESSION['launch'] != $null) {		
			header("Location: risk.php");
			$_SESSION['launch'] = $null;
			exit;
		}		
		if (isset($_SESSION['spectate']) && $_SESSION['spectate'] != $null) {	
			header("Location: spectate.php");
			$_SESSION['spectate'] = $null;
			exit;
		}					
		if ($_SESSION['RISK_USERLEVEL'] == '3') {
			$endmatch = "<form method='POST' action='$PHP_SELF?action=endmatch' style=\"display:inline;\">
			<input type='submit'  class=\"pButton\" style=\"width:100px\" value='End Match'></form>";
		} else { $endmatch = ""; }
		
		$result .= "
		<h2>".$CONFIG['risk']['gamename']."</h2>
		<table width='100%'>
		<tr><td width='40%' align=\"center\">
		<input type='button' class=\"pButton\"  style=\"width:100px\" value=' Join ' 
		onclick=\"document.location.replace('$PHP_SELF?action=launch')\"></td>   
		<td >join the game</td></tr>
		
		<tr><td width='40%' align=\"center\">
		<input type='button' class=\"pButton\"  style=\"width:100px\" value='Watch' 
		onclick=document.location.replace('$PHP_SELF?action=spectate')></td> 
		<td >spectator mode</td></tr>
		
		<tr><td width='40%' align=\"center\">
		<form method='POST' action='$PHP_SELF?action=newmatch' style=\"display:inline;\">
		<input type='submit'  class=\"pButton\" value='New Match' style=\"width:100px\"></form></td>     	
		<td >start a new match</td></tr>
		
		<tr><td width='40%' align=\"center\">$endmatch</td>     	
		<td >end current match</td></tr>
		</table>
		<br><br><center><a href='readlogs.php'>Read Logfiles</a></center><br><br>";
		return $result;
	}
	
	function display_loginform(){
		global $PHP_SELF, $errlogin;
		$result = "<h2>Login</h2>";
		if ($errlogin == '1')  {
			$_SESSION['msg'] = " Your Username and/or Password is invalid.";
		} 
		$result .= " 		
		<form method='POST' action='$PHP_SELF?action=login' style=\"display:inline;\">
		<table width=\"300px\" align=\"center\" >  
		<tr><td width=\"100px\"> Username : </td><td> <input type='text' name='username'></td></tr>
		<tr><td width=\"100px\"> Password : </td><td> <input type='password' name='password'></td></tr>
		<tr><td colspan='2' align='center'><br> <input type='submit' value='Login' class=\"pButton\"> </td></tr>
		</table><br><br>
		</form>";
		return $result;
	}
	
	function display_registerform(){
		global $CONFIG;
		$result = "
		<h2>Register</h2>
		Complete this form to register.<br>Your e-mail address is required for lost passwords only.<br>
		<form name='register' method='POST' action='register.php?&action=register'>		
		<table width=\"350px\" align=\"center\">
		<colgroup><col width=\"100px\"></col><col></col></colgroup>
		<tr><td >Your Username : </td>
			<td ><input type='text' name='username' size='40'></td> </tr>			
		<tr><td  >Your Password : </td>
			<td><input type='password' name='password' size='40'></td> </tr>
		<tr><td >Confirm Password : </td>
			<td  ><input type='password' name='confirmpassword' size='40'></td>	</tr>
		<tr><td >Your E-mail Address : </td>
			<td  ><input type='text' name='email' size='40'></td> </tr>
		<tr><td colspan='2' align='center'><br><br><input type='submit' value='Register' class=\"pButton\"><br><br></td>	</tr>
		</table></form>";
		return $result;	
	}
	
	function display_resetpwform() {
		global $CONFIG;
		$result .= "
		<h2>Reset Password</h2>
		Complete this form to reset your password.
		<br>Your new password will be e-mailed to you if the username and the e-mail match.<br>
		<form name='reset' method='POST' action='resetpw.php?action=resetpw'>
		<table width='350px' align='center'>
		<colgroup><col width=\"100px\"></col><col></col></colgroup>
		<tr><td>Your Username : </td><td><input type='text' name='username' size='40'></td></tr>
		<tr><td>Your E-mail Address :</td> <td><input type='text' name='email' size='40'></td></tr>
		<tr><td colspan='2' align='center'><br><br><input type='submit' value='Reset'  class=\"pButton\"></td></tr>
		</table></form>";		  
		return $result;
	}		
	
	function display_changepwform() {
		global $CONFIG;
		$result = "
		<h2>Change Password</h2>
		Complete this form to change your password.<br>
		<form name='changepw' method='POST' action='changepw.php?action=changepw'>
		<table width='350px' align='center'>
		<colgroup><col width=\"100px\"></col><col></col></colgroup>
		<tr><td>Current Password : </td>	<td><input type='password' name='currentpassword' size='40'></td></tr>
		<tr><td>New Password : </td> 		<td><input type='password' name='newpassword' size='40'></td></tr>
		<tr><td>Confirm Password : </td>	<td><input type='password' name='confirmpassword' size='40'></td></tr>
		<tr><td colspan='2' align='center'><br><br>	<input type='submit' value='Change' class=\"pButton\"></td></tr>		
		</table></form>";
		return $result;		
	}
	
	function display_serverinfo() {
		global $CONFIG;
		$cdb = new class_mysql;
		$cdb->select("SELECT count(*) from risk_players where num > 6");
		$row 	 	= $cdb->fetchArray();
		$countall 	= $row[0];
		$cdb->select("SELECT CurrentGame, NumOnline, StartedBy from risk_config");
		$row 	 	= $cdb->fetchArray();
		$CurrentGame 	= $row['CurrentGame'];
		$numonline 	= $row['NumOnline'];
		$StartedBy 	= $row['StartedBy'];
		
		$r = "<h2>Server Info</h2>
		<table width=\"90%\">
		<tr><th colspan=2>".$CONFIG['risk']['servername']."</th> </tr>
		<tr><td>Registered User: </td> <td>$countall</td> </tr>
		<tr><td>Online User: </td> <td>$numonline</td> </tr>
		<tr><td>Game Name:</td><td>".$CONFIG['risk']['gamename']."</td> </tr>
		<tr><td>Game Status: </td> <td>$CurrentGame</td> </tr>
		<tr><td>Started By: </td> <td>$StartedBy</td> </tr>
		</table>
		";
		return $r;
	}
	
	function display_halloffame() {
		$r = "<h2>Hall Of Fame</h2>
		<table width=\"90%\">
		<tr><th>Rank</th> <th>Username</th> <th>Points</th></tr>";
		$cdb = new class_mysql;
		$cdb->select("SELECT victories, losses, takeovers, kills,
					((victories * 10) - (losses * 5) + (takeovers) + (kills *5)) as points, 
					username FROM risk_players
					where num > 6  order by points DESC
					LIMIT 10");
						$i = 1;
		while($daten = $cdb->fetchArray() ) {
			$username = $daten['username'];
			$victories = $daten['victories'];
			$losses = $daten['losses'];
			$kills = $daten['kills'];
			$takeovers = $daten['takeovers'];
			$points = (($victories * 10) - ($losses * 5) + ($takeovers) + ($kills *5));
			if($points > 0) {
			$r .= "<tr><td>$i.</td><td>$username</td> <td>$points</td></tR>";
			$i++;
			}
		}
		if($i ==1) {
			$r .= "<tr><td colspan=\"3\">Hall of Fame is empty</td></tR>";			
		}
		$r .= "</table>";
		return $r;
	}
	
	function display_adminpanel() {
		global $CONFIG;
		if ($_SESSION['RISK_USERLEVEL'] == '3'){
			$result = "
			<h2>Risk Admin</h2>
			<table width='90%'>
			<tr><th>Username</th><th>Email</th><th>Userlevel</th><th>&nbsp;</th></tr>";
		  
			$cdb 		= new class_mysql;
			$cdb->select("SELECT * FROM risk_players where num > 6 order by username");
			if($cdb->getRecords() > 0) {
				while($row    	= $cdb->fetchArray()) {
					$username 	= $row['username'];
					$userlevel 	= $row['level'];
					$email 		= $row['email'];
					$num 		= $row['num'];
					$useredit 	= "<a href=\"riskadmin.php?action=edituser&userid=$num\">edit</a>";
					$result    .= "<tr><td>$username</td><td>$email</td><td>$userlevel</td><td>$useredit</td></tr>";
				}
			} else {	}
			$result .= "</table>";
		} else { $result = "Permission Denied"; }
		return $result;
	}	
	
	function display_adminEditUserForm() {
		global $CONFIG, $userid;
		if ($_SESSION['RISK_USERLEVEL'] == '3') {
			$cdb 		= new class_mysql;
			$cdb->select("SELECT * FROM risk_players where num = '$userid'");
			$row    	= $cdb->fetchArray();
			$username 	= $row['username'];
			$userlevel 	= $row['level'];
			$email 		= $row['email'];
			$result 	= "
			<h2>Risk Admin - Edit User</h2>
			
			<table width='90%' >
			<tr><th> Userdata </th></tr>
			<tr><td align='center'>Username: $username<br> Email: $email<br> Level: $userlevel<br> </td>
			</tr></table>
			
			<form method='POST' action='riskadmin.php?action=changelevel'>
			<input type='hidden' name='username' value='$username'>
			<table width='90%' >
			<colgroup> <col width=\"100px\"></col> <col width=\"100px\"></col> <col></col></colgroup>
			<tr><th colspan=3>Change Levels</th></tr>
			<tr><td >Level :</td>
			<td><select name='level'>
			  <option value='1'>User</option>
			  <option value='2'>Administrator</option>
			  <option value='3'>Super Admin</option></select></td>
			<td><input type='submit' value='Change' class=\"pButton\"></td></tr>
			</table></form>
			
			<form method='POST' action='riskadmin.php?action=deleteuser'>
			<input type='hidden' name='username' value='$username'>
			<table width='90%' >
			<colgroup> <col width=\"100px\"></col> <col width=\"100px\"></col> <col></col></colgroup>
			<tr><th colspan=3>Delete Users</th></tr>
			<td>Confirm :</td>
			<td><input type='checkbox' name='confirm'></td>
			<td><input type='submit' value='Delete' class=\"pButton\"></td></tr>
			</table></form>";
			
		} else { $result = "Permission Denied"; }
		return $result;
	}
	
	function display_risk() {	
		global $CONFIG;
		if(isset($_GET['action']) && ($_GET['action'] == "start")) { $this->risk_start(); }
		$this->risk_init();				
		$cdb = new class_mysql;
		$cdb->select("SELECT color FROM risk_colors WHERE assigned='".$_SESSION['RISK_USERNUM']."'");
		$dacount = $cdb->getRecords();
		if ($dacount > 0) {	
			$row      = $cdb->fetchArray();
			$mycolor  = $row['color'];
		} else { $mycolor = false; }
		
		$CurrentGame = $this->CurrentGame;
		
		$r 			 = "";	 
		if($mycolor == false) {
			$colorselecta = $this->risk_display_colorselecta();
			$result = "";
			$r .= "
			<div  class=\"outer\">			
			<div class=\"inner1\"> </div>
			<div class=\"inner2\">
			<div style=\"margin-left:10px;margin-right:10px;\">
			<h2>".$CONFIG['risk']['gamename']." - join the game</h2>
			$colorselecta </div></div>
			<div class=\"inner4\"> </div>
			<div class=\"inner3\"> </div>
			</div>
			<form name='main' onsubmit='return false' style='display:inline;'>
			<input type='hidden' name='currentgame' value='$CurrentGame'> 
			</form>	";
			
		}else if($CurrentGame == "Starting"){
		$lobby		 = $this->risk_display_cardsAndPlayer('spectate');
			$startoptions = $this->risk_display_startoptions();
			$mapfader 		= $this->risk_display_mapfader();
			$r .= "
			<div  class=\"outer\">
			<div id=\"head\"><h2>PHP RISK - ".$CONFIG['risk']['version']." - ".$CONFIG['risk']['gamename']." - start the game</h2></div>
			<div id=\"lobby\">$lobby
			<div style=\"margin-left:10px;margin-right:10px;\"> </div>			
			</div>
			<div id=\"riskmap\">$startoptions</div>
			
			<div id=\"risksmallmap\">$mapfader</div>
			<div id=\"tabs\">
			<form name='source' onsubmit='return false' style=\"display:inline;\">
			<div class=\"pButton\" style=\"padding:3px;width:100%;\">Log</div>
			<input type='hidden' name='t' value='3'>
			</form>	</div>
			<div id=\"tabsource\"></div>
			
			</div>	
			<form name='main' onsubmit='return false' style='display:inline;'>
			<input type='hidden' name='currentgame' value='$CurrentGame'> 
			</form>";
		} else if($CurrentGame != "Starting" && ($_SESSION['RISK_TURNORDER']>0)) {
			$bottomsrc   	= $this->bottomsrc;
		$lobby		 = $this->risk_display_cardsAndPlayer();
			$mapoverlay 	= $this->risk_display_mapoverlay();
			$mapfader 		= $this->risk_display_mapfader();
			$tabs 			= $this->risk_display_tabs();
			$r .= "
			<div class=\"outer\">
			<div id=\"head\"><h2>PHP RISK - ".$CONFIG['risk']['version']." - ".$CONFIG['risk']['gamename']."</h2></div>
			<div id=\"lobby\">$lobby</div>
			<div id=\"riskmap\">$mapoverlay</div>
			<div id=\"risksmallmap\">$mapfader</div>
			<div id=\"tabs\">$tabs</div>
			<div id=\"tabsource\"></div>
			<div id='bottom'></div>
			<div id=\"turnmsg\">
			<form name='main' onsubmit='return false' style='display:inline;'>
			<input type='text' name='cturn' style='text-align:center; font-weight:bold; width:100%;'>
			<input type='hidden' name='myturn' value='0'>
			<input type='hidden' name='turnstatus' value=''> 
			<input type='hidden' name='currentgame' value='$CurrentGame'> 
			</form></div>
			<script language=\"javascript\">
			DisplayBottom('$bottomsrc');
			</script></div>";
		} 
		$r .= "<span id=\"ton1\"></span>";	
		return $r;
	}
	
	function display_spectate() {
		global $CONFIG;	
		unset($_SESSION['RISK_LASTREQUEST']);
		unset($_SESSION['RISK_LASTCHATREQUEST']);
		$mapoverlay 	= $this->risk_display_mapoverlay();
		$mapfader 		= $this->risk_display_mapfader();
		$lobby		 = $this->risk_display_cardsAndPlayer('spectate');
		$r .= "
		<div class=\"outer\">
			<div id=\"head\"><h2>PHP RISK - ".$CONFIG['risk']['version']." - ".$CONFIG['risk']['gamename']."</h2></div>
			<div id =\"lobby\">$lobby</div>
			<div id=\"riskmap\">$mapoverlay</div>
			<div id=\"risksmallmap\">$mapfader</div>
			<div id=\"tabs\">
			<form name='source' onsubmit='return false' style=\"display:inline;\">
			<div class=\"pButton\" style=\"padding:3px;width:100%;\">Log</div>
			<input type='hidden' name='t' value='3'>
			</form>	</div>
			<div id=\"tabsource\"></div>
			<div id=\"turnmsg\">
			<form name='main' onsubmit='return false' style=\"display:inline;\">
			<input type='hidden' name='turnstatus' value='0'>
			<input type='text' name='cturn' style='text-align:center; font-weight:bold; width:100%;'>
			</form>
			</div>
		</div>";
		return $r;
	}
	function risk_display_tabs() {			
		$t = $_GET['t']; 	
		if($t == "") { $t = 1; }
		switch ($t) {
		  case 1: $t1 = 'tabon'; $t2 = 'taboff'; $t3 = 'taboff'; break;
		  case 2: $t2 = 'tabon'; $t1 = 'taboff'; $t3 = 'taboff'; break;
		  case 3: $t3 = 'tabon'; $t1 = 'taboff'; $t2 = 'taboff'; break;
		}		
		$result =  "
		 <form name='source' onsubmit='return false' style=\"display:inline;\">
		  <input type='hidden' name='t' value='$t'>
		 </form>
		 
		 
		 <script language=\"javascript\">
			function onClickTab(t) {
				for(var i=1;i<4;i++) {
					var mytab = 't'+i;
					if(i==t) {
						document.getElementById(mytab).className = 'tabon';
					} else {
						document.getElementById(mytab).className = 'taboff';
					}			
				}
				document.source.t.value=t;
			}
		 </script>
		 <table width='100%' cellpadding='0' cellspacing='0'>
		  <tr>
		   <td class='$t1' id='t1' width='33%'
		   onmouseover=this.className='thover' 
		   onmouseout='if(document.source.t.value==1){this.className=\"tabon\"; } else {  this.className=\"taboff\"; }'
		   onclick='onClickTab(1);setArmies();'>Armies</td>    
		   <td class='$t2' id='t2' width='33%' 
		   onmouseover=this.className='thover' 
		   onmouseout='if(document.source.t.value==2){this.className=\"tabon\"; } else {  this.className=\"taboff\"; }'
		   onclick='onClickTab(2);setDialog();'>Chat </td>
		   <td class='$t3' id='t3' width='33%' 
		   onmouseover=this.className='thover' 
		   onmouseout='if(document.source.t.value==3){this.className=\"tabon\"; } else {  this.className=\"taboff\"; }'
		   onclick='onClickTab(3);setLog();'>Log</td>
		  </tr>
		 </table>
		 <script language=\"javascript\">
		 document.source.t.value=$t;
		 //xajax_getTabsource(\"$t\");
		 </script>
		 ";
		return $result;			
	}
	
	function risk_display_cardsAndPlayer($type='chat') {
		global $nojoin, $PHP_SELF;
		$cdb = new class_mysql;
		$cdb->select("SELECT color FROM risk_colors WHERE assigned='".$_SESSION['RISK_USERNUM']."'");
		$row      = $cdb->fetchArray();
		$mycolor  = $row['color'];		
		if(!isset($nojoin)){
			$cdb->insert("INSERT INTO risk_dialog VALUES('1', '".date("Y-m-d H:i:s")."', 
						  '<font color=\'$mycolor\'>* ".$_SESSION['RISK_USERNAME']." has joined the lobby.</font>')");
		}		
		$result = "			
		<form method=\"post\" name=\"xajaxmsgform\" onSubmit=\"return false;\" style=\"display:inline;\">
		<input type=\"hidden\" name=\"xajaxmsg\" value=\"$type\">
		</form>
		<form name='playerlist' id='playerlist' onsubmit='return false' style='display:inline;'>
		<table width='800px'height='140px' cellpadding=1 cellspacing=1 border=0> 
		<colgroup>
		<col width=\"100px\"></col>
		<col width=\"100px\"></col>
		<col width=\"100px\"></col>
		<col width=\"100px\"></col>
		<col width=\"100px\"></col>
		<col width=\"100px\"></col>
		<col width=\"200px\"></col>
		</colgroup>
		<tr valign='top' height='30px'>
		<td><input type='button' name='p1' class='p1' onclick='SpeakTo(this)'></td>
		<td><input type='button' name='p2' class='p2' onclick='SpeakTo(this)'></td>
		<td><input type='button' name='p3' class='p3' onclick='SpeakTo(this)'></td>
		<td><input type='button' name='p4' class='p4' onclick='SpeakTo(this)'></td>
		<td><input type='button' name='p5' class='p5' onclick='SpeakTo(this)'></td>
		<td><input type='button' name='p6' class='p6' onclick='SpeakTo(this)'></td>
		<td rowspan=2 align='center'>
		<input type='button' name='quit'  value='Quit' onclick=\"riskquit();\"	style=\"width:100px\"><br><br>";
		if($type == "chat") {
			$result .= "
			<input type='button' name='trade' value='Trade In' onclick=\"TradeCards()\" style=\"width:100px\">";
		}
		$result .= "
		</form>	</td></tr>
		<tr valign='top'>
		<td><div id='p1_cards'>&nbsp;</div></td>
		<td><div id='p2_cards'>&nbsp;</div></td>
		<td><div id='p3_cards'>&nbsp;</div></td>
		<td><div id='p4_cards'>&nbsp;</div></td>
		<td><div id='p5_cards'>&nbsp;</div></td>
		<td><div id='p6_cards'>&nbsp;</div></td>
		</tr></table>";		
		return $result;
	}
	
	
	function risk_display_colorselecta() {
		global $PHP_SELF;
		$cdb 	= new class_mysql;
		$cdb2 	= new class_mysql;
		$cdb->select("SELECT CurrentGame from risk_config");
		$row    = $cdb->fetchArray();
		$CurrentGame = $row['CurrentGame'];
		if($CurrentGame == 'Starting') {
			$cdb->select("SELECT c.colornum, c.color FROM risk_colors c where c.assigned <= 6 ORDER BY c.colornum");		
		} else {		
			$cdb->select("SELECT c.colornum, c.color FROM risk_colors c, risk_players p 
			where c.assigned <= 6 and p.turnorder > 0 and (c.assigned = p.num) ORDER BY c.colornum");
		}
		$dacount2 = $cdb->getRecords();
		if ($dacount2 == 0) {
			return "This match is full!";			
		} else {
			$myselect = "<select name=\"selcolor\" style=\"width:100px;\">";
			while($row      = $cdb->fetchArray()) {
				$mycolor  	= $row['color'];
				$mycolornum = $row['colornum'];
				$assigned   = $row['assigned'];
				$myselect  .= "<option value=\"$mycolornum\">$mycolor</option>\n";
			}
			$myselect .= "</select>";			
			
			$result = "
			<h3>Please select your color</h3>
			<form method=\"post\" name=\"xajaxmsgform\" onSubmit=\"return false;\">
			<input type=\"hidden\" name=\"xajaxmsg\" value=\"nochat\">
			</form>
			<form method=\"post\" name=\"msg\" action=\"$PHP_SELF\">
			<table width=\"100%\">
			<tr>
			<td><b>color</b><br>$myselect</td>
			<td>
			<input type=\"hidden\" name=\"maptype\" value=\"2d\" > 
			<!-- <b>maptype</b><br>
			<input type=\"radio\" name=\"maptype\" value=\"2d\" checked> 2d Map &nbsp;&nbsp;&nbsp;
			<input type=\"radio\" name=\"maptype\" value=\"3d\"> 3d Map--></td></tr>
			<tr>
			<td colspan=2 align='center'><br><br> 
			<input type='button' name='quit'   value='Quit' onclick=\"riskquit();\"  style='color:red;width:100px;' >
			<input type='submit' name='submit' value='Join' style='color:green;width:100px;'  ></td></tr>
			</table>
			</form>";
			return $result;
		}
	}
	
	function risk_display_startoptions() {
		$result = "";
		$cdb = new class_mysql;
		$cdb->select("SELECT StartedBy, CurrentGame FROM risk_config");
		$daten     		= $cdb->fetchArray();
		$StartedBy 		= $daten['StartedBy'];
		$CurrentGame 	= $daten['CurrentGame'];
		if (($StartedBy == $_SESSION['RISK_USERNAME']) && ($CurrentGame == "Starting")) {
			$result .= "<h2>Start Game Options</h2>
			<center>
			<form name='startform' action='$PHP_SELF?action=start&nojoin=true' method='POST' style='display:inline;'>			
			<table width='100%' cellpadding=0 cellspacing=0 border=0  style='display:inline;' > 
			<colgroup><col width=\"150px\"><col></colgroup>
			<tr valign=top><td>
			<input type='radio' name='autodeploy' value='1' CHECKED> Auto Deploy<br>
			<input type='radio' name='autodeploy' value='0' > Manual Deploy	<br><br></td>
			<td>Select Auto Deploy to let the computer place your armies randomly. </td></tr>
			<tr valign=top><td>
			Additional Start Armies<br>
			<select name=\"startarmies\" style=\"width:100px;\">";
			for($i=0;$i<=100;$i++) {
				$result .= "<option value=\"$i\">$i</option>";
			}
			$result .= "</select><br><br></td><td>Select some additional armies to deploy at the beginning.</td></tr>
			<tr valign=top><td>
			Number of Players<br>
			<select name=\"numplayers\"  style=\"width:100px;\">";
			for($i=2;$i<=6;$i++) {
				$result .= "<option value=\"$i\">$i</option>";
			}
			$result .= "</select><br><br></td><td>Number of players in the game. If you choose more players than logged in,<br> the stupid 
			Alies-Bots 0.1 will fight against you with the not-choosen-colors.  </td></tr>
			</table><br><br><br><br>
			<input type='submit' name='start' value='Start' style='color:green;width:100px;' >
			</form></center>";
		} else {
			$result .= "<h2>Please wait while $StartedBy sets up the start options and starts the game...</h2>";
		}
		return $result;
	}
		
	function risk_display_mapfader() {
		if ($_SESSION['maptype'] == "3d") {
			$r = "<iframe name='mapfader' src='3dmapfader.php' width='100%' height='130px' frameborder='0' scrolling='no'></iframe>";
		} else {
			$r = "<div style=\"width:100%;height:130px;\">
			<div id=\"parentriskfader\"  style=\"position:absolute;top:0px;left:0px;width:200px;height:100px;\"></div>
			</div>";
		}
		return $r;
	}	
	
	function risk_display_mapoverlay() {	
		$cdb = new class_mysql;		
		$cdb->select("SELECT TurnStatus FROM risk_config");
		$row = $cdb->fetchArray();
		$_SESSION['TurnStatus'] = $row['TurnStatus'];
		
		if ($_SESSION['maptype'] == "3d") {

			$r = "
			 <script language='javascript'>		 
			   
				function updateCountry(name,value,r,g,b){
					Cortona1.Engine.RootNodes(\"S\").Fields(\"country_\" + name).Value = name;
					Cortona1.Engine.RootNodes(\"S\").Fields(\"countryval_\" + name).Value = value;
					Cortona1.Engine.RootNodes(\"S\").Fields(\"r_countrycol_\" + name).Value = r;
					Cortona1.Engine.RootNodes(\"S\").Fields(\"g_countrycol_\" + name).Value = g;
					Cortona1.Engine.RootNodes(\"S\").Fields(\"b_countrycol_\" + name).Value = b;
					
				}				
				function updateRotation(xx,yy){					
					Cortona1.Engine.RootNodes(\"drehscript\").Fields(\"kugelx\").Value = xx;
					Cortona1.Engine.RootNodes(\"drehscript\").Fields(\"kugely\").Value = yy;
				}				
				function zoomCam(xx){
					Cortona1.Engine.RootNodes(\"drehscript\").Fields(\"naehe\").Value = xx;
				}				
			 </script>
			 ";

			$r .= '	
			<OBJECT id="Cortona1" style="WIDTH: 600px; HEIGHT: 350px" 
			classid="clsid:86A88967-7A20-11D2-8EDA-00600818EDB1">
			<PARAM NAME="SRC" VALUE="3dindex.wrl.php"
			codebase="http://www.parallelgraphics.com/bin/cortvrml.cab#Version=4,2,0,93"> 
			<!--<param name="Skin" value="{46BB95BF-8EB4-481A-A1EF-50D43FC32B9D};http://www.parallelgraphics.com/bin/cad.zip">-->
			</object>';	
		/*
			$r .= '	
			<EMBED id="Cortona1" SRC="3dindex.wrl.php"
			TYPE="model/vrml"
			WIDTH="660"
			HEIGHT="410"
			VRML_SPLASHSCREEN="FALSE"
			VRML_DASHBOARD="FALSE"
			CONTEXTMENU="FALSE">';
	*/
		} else {
			$r = "			
			<script language=\"javascript\">
				function updateCountry(country,armies,r,g,b) {
					document.getElementById('div'+country).innerHTML = armies+'<br>';
					document.getElementById('div'+country).style.color = 'rgb('+r+','+g+','+b+')';
				}
			</script>
			<div id=\"overlay\" style=\"width:540px;height:327px;left:20px; position:absolute; background-image:url(maps/map.jpg);
			background-repeat:no-repeat;\">";
			
			$cdb->select("SELECT risk_countries.armies,  2d_top , 2d_left, risk_countries.num, risk_players.color as color,
						risk_countries.name			FROM risk_countries 
						 LEFT JOIN risk_players ON risk_countries.owner = risk_players.num
						 ORDER BY risk_countries.num");

			while ($row = $cdb->fetchArray()) {
				$c = $this-> getColor($row['color'],'rgb');
				$cleaname 	= str_replace(" ", "_", $row['name']);
				 $r .= "<div title=\"".$row['num']." - $cleaname\" id='div".$cleaname."' style='font-family:Arial,Helvetica,Sans Serif; 
						font-size:14px; font-weight:bold; 
						line-height:20px;
						color:rgb(".$c[0].",".$c[1].",".$c[2].");
						 background-image:url(\"maps/textbg.gif\");
						top:".round($row['2d_top'] * 0.8 -10)."px;
						left:".round($row['2d_left'] * 0.8 - 10)."px; 
						width:30px; height:30px;
						text-align:center;
						position:absolute; cursor:pointer; '
						onmousedown='SelCountry(".$row['num'].")'>	".$row['armies']." </div>\n";
			}
			$r .= "</div>";
		}
		return $r;
	}	
	
	function getTurnmsg() {
		global $CONFIG;
		$yourturnmsg = "";
		for($i=1;$i < 10;$i++) {
			$yourturnmsg .= $CONFIG['risk']['yourturnmsg']." ";
		}
		return $yourturnmsg;
	}
	
	function check4botmove() {
		$cdb = new class_mysql;
		$bot = new class_riskbot;
		$cdb->select("SELECT num from risk_players where turnflag='1' and num <= 6");
		if($cdb->getRecords() > 0) {
			$daten = $cdb->fetchArray();
			$num = $daten[0];
			$bot->botmove($num);
		}
	}
	
	function countriesByContinent($continent) {
		$cdb = new class_mysql;
		$cdb->select("SELECT count(*)  FROM risk_countries where continent='$continent'");
		$daten = $cdb->fetchArray();
		return $daten[0];
	}
	
	function playerById($playerid) {
		if($playerid == "") { return false; }
		$cdb = new class_mysql;
		$cdb->select("select username from risk_players where num = '$playerid' ");
		$daten = $cdb->fetchArray();
		return $daten[0];	
	}
	
	function countryById($cid) {
		if($cid == "") { return false; }
		$cdb = new class_mysql;
		$cdb->select("select name from risk_countries where num = '$cid' ");
		$daten = $cdb->fetchArray();
		return $daten[0];	
	}
	
	function continentById($cid) {
		if($cid == "") { return false; }
		$cdb = new class_mysql;
		$cdb->select("select name from risk_continents where num = '$cid' ");
		$daten = $cdb->fetchArray();
		return $daten[0];	
	}
		
	function getColor($colorname,$type='rgb') {	
		if		($colorname == 'white') { $r = 255;  $g = 255;  $b = 255; } 
		else if	($colorname == 'green') { $r = 0;  	 $g = 255;  $b = 0; } 
		else if ($colorname == 'red') 	{ $r = 255;  $g = 0; 	$b = 0; } 
		else if ($colorname == 'blue')  { $r = 51;   $g = 204;  $b = 255; } 
		else if ($colorname == 'yellow'){ $r = 255;  $g = 255;  $b = 0; } 
		else if ($colorname == 'gray')  { $r = 150;  $g = 150;  $b = 150; } 
		else if ($colorname == 'pink')  { $r = 255;  $g = 0; 	$b = 204; } 
		else 							{ $r = 0;  	 $g = 0; 	$b = 0; }		
		if($type == "rgb") { return array($r,$g,$b); }	
	}
	
	
	function getUserNamePass($usernum) {
		$cdb = new class_mysql;
		$cdb->select("select username,password from risk_players where num = '$usernum'");
		$daten = $cdb->fetchArray();
		$username = $daten['username'];
		$password = $daten['password'];
		return array($username,$password);
	}
	
	function game_getPlayerAndCards($menum) {
		$cdb 	= new class_mysql;
		$cdb2 	= new class_mysql;
		$player = array();		
		$cdb->select("SELECT risk_players.num, colornum, username FROM risk_colors
					  LEFT JOIN risk_players ON (risk_colors.assigned = risk_players.num) ORDER BY colornum");
		while ($row = $cdb->fetchArray()) {
			$colornum 	= $row['colornum'];
			$username 	= $row['username'];
			$num 		= $row['num'];
			if($num != 0) {
				if($num == $menum) { $mine = 'true'; } else { $mine = 'false'; }
				$cdb2->select("SELECT num, symbol, name FROM risk_cards WHERE owner='$num'");
				$count  = $cdb2->getRecords();
				$r 		= array();
				while ($row2 = $cdb2->fetchArray())  {
					$r[] = array($row2['num'],$row2['name'],$row2['symbol']);
				}
				$player[] = array($colornum,$username,$num,$mine,$r);
			}			
		}	
		return $player;
	}
	
	
	function assignColor($playernum,$colornum) {
		$cdb = new class_mysql;		
		$cdb->query("UPDATE risk_colors SET assigned='$playernum' WHERE colornum='$colornum'");		  
		$cdb->select("select color from risk_colors where colornum='$colornum'");
		$daten = $cdb->fetchArray();
		$color = $daten[0];
		$cdb->select("select armies, turnorder, turnflag, num from risk_players where color='$color'");
		$daten = $cdb->fetchArray();
		$oldplayer = $daten['num'];
		if($oldplayer != $playernum) {
			$cdb->update("update risk_players set armies = '".$daten['armies']."', turnflag = '".$daten['turnflag']."'
			, turnorder = '".$daten['turnorder']."', color = '$color', rejoinflag = 1, status='10' where  num='$playernum' ");	
			if($oldplayer > 0) {			
				$cdb->update("update risk_players set armies = '0', turnorder = '0', turnflag = '0', color='', status='1' 
							  where  num='$oldplayer' ");
				$cdb->update("update risk_countries set owner='$playernum' where owner = '$oldplayer'");
				$cdb->update("update risk_continents set owner='$playernum' where owner = '$oldplayer'");
				$cdb->update("update risk_cards set owner='$playernum' where owner = '$oldplayer'");
			}
		}
	}	
	
	function main_init($show='default') {
		global $CONFIG;
		if(isset($_GET['action']) && ($_GET['action']=='login')) {
			$this->risk_login();
		}
		if(isset($_GET['action']) && ($_GET['action'] == "logout")) { 
			$this->risk_logout();
		}
		if(isset($_GET['action']) && ($_GET['action'] == "register")) { 
			$this->register();
		}
		if(isset($_GET['action']) && ($_GET['action'] == "resetpw")) { 
			$this->resetpw();
		}
		
		if(isset($_GET['action']) && ($_GET['action'] == "changelevel")) { 
			$this->adminChangeLevel();
		}
		if(isset($_GET['action']) && ($_GET['action'] == "deleteuser")) { 
			$this->adminDeleteUser();
		}
		
		if (!isset($_SESSION['RISK_USERNUM'])) { 
			if($show == "default") {
				$result = $this->display_loginform();
			} elseif($show == "showvalue") {
				$result = $showvalue; 
			} elseif($show == "register") {
				$result = $this->display_registerform(); 
			} elseif($show == "resetpw") {
				$result = $this->display_resetpwform(); 
			}
			$leftframe = "
			<h2>Welcome Guest</h2>";
				if($CONFIG['risk']['master']['enable'] == true) {
					$leftframe .= "
					<a href='".$CONFIG['risk']['master']['url']."'>Risk Master</a><br>";			
				}
				$leftframe .= "
			<a href='index.php'>Login</a><br>
			<a href='register.php'>Register</a><br>
			<a href='resetpw.php'>Reset Password</a>  ";
			$rightframe  = $this->display_serverinfo();
			$rightframe .= $this->display_halloffame();
			$result = "
			<div  class=\"outer\">
			<div class=\"inner1\"><div style=\"margin-left:10px;margin-right:10px;\">$leftframe</div></div>
			<div class=\"inner2\"><div style=\"margin-left:10px;margin-right:10px;\">$result</div></div>
			<div class=\"inner3\"><div style=\"margin-left:10px;margin-right:10px;\">$rightframe</div></div>		
			<div class=\"inner4\"><div class=\"copyright\" style=\"position:absolute;top:190px;left:200px;\">".$CONFIG['risk']['copyright']."</div></div>		
			</div>	";
		} else { 
			$this->loginCheck();
			$this->risk_launch();
			$this->risk_spectate();
			$this->risk_newmatch();
			$this->risk_endmatch();
			$null 	= NULL;		
			if(isset($_GET['action']) && ($_GET['action'] == "changepw")) { 
				$this->changepw();
			}
			if (isset($_SESSION['launch']) && $_SESSION['launch'] != $null) {		
				header("Location: risk.php");
				$_SESSION['launch'] = $null;
				exit;
			}		
			if (isset($_SESSION['spectate']) && $_SESSION['spectate'] != $null) {	
				header("Location: spectate.php");
				$_SESSION['spectate'] = $null;
				exit;
			}
		
			if($show == 'risk') {
				$result = $this->display_risk();
				
			} elseif($show == 'spectate') {
				$result = $this->display_spectate();
			} else {
				if($show == 'logfiles') {
					$result = $this->display_logfiles();	
				} elseif($show == 'win') {
					$result = $this->display_win();	
				}  elseif($show == 'changepw') {
					$result = $this->display_changepwform();	
				}  elseif($show == 'gamelist') {				
					$result = $this->display_gamelist();					
				}  elseif($show == 'riskadmin') {
					if(isset($_GET['action']) && ($_GET['action'] == "edituser")) { 
						$result = $this->display_adminEditUserForm();
					} else {
						$result = $this->display_adminpanel(); 
					}
				} else {
					$result = "<img src=\"maps/cover.jpg\">";	
				}
				$leftframe = "
				<h2>Welcome ".$_SESSION['RISK_USERNAME']."</h2>
				<a href='index.php?action=logout'>Logout</a><br>
				<a href='changepw.php'>Change Password</a><br><br>";
				if($CONFIG['risk']['master']['enable'] == true) {
					$leftframe .= "
					<a href='".$CONFIG['risk']['master']['url']."'>Risk Master</a><br>
					<a href='gamelist.php'>All Games</a><br>";			
				}
				if ($_SESSION['RISK_USERLEVEL'] == '3') {
					$endmatch  = "<a href='$PHP_SELF?action=endmatch'>End Match</a><br>";
					$riskadmin = "<a href='riskadmin.php'>Risk Admin</a><br>";
					
				} else { $endmatch = ""; }
				$leftframe .= "
				<h2>This Game</h2>
				<a href='index.php'>".$CONFIG['risk']['gamename']."</a><br>
				<a href=\"index.php?action=launch\">join the game</a><br>
				<a href=\"index.php?action=spectate\">spectator mode</a><br>
				<a href=\"index.php?action=newmatch\">New Match</a><br>
				$endmatch
				<a href='readlogs.php'>Read Logfiles</a><br>
				$riskadmin
				";	
				$rightframe  = $this->display_serverinfo();
				$rightframe .= $this->display_halloffame();
				$result = "
				<div  class=\"outer\">
				<div class=\"inner1\"><div style=\"margin-left:10px;margin-right:10px;\">$leftframe</div></div>
				<div class=\"inner2\"><div style=\"margin-left:10px;margin-right:10px;\">$result</div></div>
				<div class=\"inner3\"><div style=\"margin-left:10px;margin-right:10px;\">$rightframe</div></div>		
				<div class=\"inner4\"><div class=\"copyright\" style=\"position:absolute;top:190px;left:200px;\">".$CONFIG['risk']['copyright']."</div></div>		
				</div>	";
			}
		}
		$this->printwebsite($result);
	}
	
	function printwebsite($content="") {
		global $CONFIG;		
		require_once ('xajaxCommon.php');
		$xajaxjs = $xajax->getJavascript('');
		
		if (isset($_SESSION['msg']) && $_SESSION['msg'] != "") {
			$msg = "<br><div class='msg' id='msg'>".$_SESSION['msg']."</div>";
			$_SESSION['msg'] = "";
		} else { $msg = ""; }	
		$stylelink = $this->get_style_link();
		echo "
		<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">
		<html><head>
		  <title>The object of war is not to die for your country... it's to make the other bastard die for his.</title>
		  $stylelink
		  $xajaxjs		  
		  <script src=\"risk_js.js\" type=\"text/javascript\"></script> 
		</head><body style=\"overflow:hidden;\">
		$msg 
		$content</body></html>";
	}
}

?>